import Vue from 'vue'
import VueRouter from 'vue-router'
import API from '../axios/api'
import '../axios/instance'

Vue.use(VueRouter)

const routes = [{
    path: '/',
    name: 'Recommendation',
    meta: { title: '个性推荐', isAuth: true },
    component: () =>
        import ('../../views/Recommendation/Recommendation.vue'),
}, {
    path: '/exclusivecustom',
    name: 'ExclusiveCustom',
    meta: { title: '专属定制', isAuth: true },
    component: () =>
        import ('../../views/ExclusiveCustom/ExclusiveCustom.vue'),
}, {
    path: '/songlist',
    name: 'SongList',
    meta: { title: '歌单', isAuth: true },
    component: () =>
        import ('../../views/SongList/SongList.vue'),
}, {
    path: '/rankinglist',
    name: 'RankingList',
    meta: { title: '排行榜', isAuth: true },
    component: () =>
        import ('../../views/RankingList/RankingList.vue'),
}, {
    path: '/singer',
    name: 'Singer',
    meta: { title: '歌手', isAuth: true },
    component: () =>
        import ('../../views/Singer/Singer.vue'),
}, {
    path: '/latestmusic',
    name: 'LatestMusic',
    meta: { title: '最新音乐', isAuth: true },
    component: () =>
        import ('../../views/LatestMusic/LatestMusic.vue'),
}, {
    path: '/login',
    name: 'Login',
    meta: { title: '登录', isAuth: false },
    component: () =>
        import ('../../views/Login/Login.vue'),
}, {
    path: '/playlist',
    name: 'Playlist',
    meta: { title: '歌单详情', isAuth: true },
    component: () =>
        import ('../../views/Playlist/Playlist.vue'),
}]

const router = new VueRouter({
    routes
})



router.beforeEach((to, from, next) => {
    console.log('前置路由守卫：', to, from);
    if (to.meta.isAuth === true) { //判断是否需要鉴权
        if (localStorage.getItem('token') && Vue.prototype.getCookie('cookie')) {
            API.login.status().then(res => {
                console.log(res);
                if (res.data.account !== null) {
                    next();
                } else next({ name: 'Login' })
            })
        } else next({ name: 'Login' })
    } else next()
});


// 全局后置守卫，初始化时执行，每次路由切换后执行
router.afterEach((to) => {
    document.title = to.meta.title || '首页'; //修改网页的title
})

export default router